import { computed, onMounted, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { useListPage } from "@/composables/useListPage";
import accountsApi, {
  type AccountItem,
  type AccountPayload,
  type AccountListResult
} from "@/api/access/accounts";
import rolesApi, {
  type RoleItem,
  type RoleListResult
} from "@/api/access/roles";
import { ensureArray, toNumber } from "@/api/_helpers";

interface AccountFilterForm {
  keyword: string;
  status: string | number;
  role_id: string | number;
}

interface AccountFormModel {
  id: number;
  phone: string;
  nickname: string;
  real_name: string;
  email: string;
  password: string;
  status: number;
  role_ids: Array<number>;
}

const DEFAULT_FILTER: AccountFilterForm = {
  keyword: "",
  status: "",
  role_id: ""
};

const DEFAULT_FORM: AccountFormModel = {
  id: 0,
  phone: "",
  nickname: "",
  real_name: "",
  email: "",
  password: "",
  status: 1,
  role_ids: []
};

const STATUS_OPTIONS = [
  { label: "全部状态", value: "" },
  { label: "已启用", value: 1 },
  { label: "已禁用", value: 0 }
];

const columns: TableColumnList = [
  { label: "用户ID", prop: "id", width: 90 },
  { label: "手机号", prop: "phone", minWidth: 150, align: "left" },
  { label: "姓名", prop: "real_name", minWidth: 140, align: "left" },
  { label: "昵称", prop: "nickname", minWidth: 140, align: "left" },
  {
    label: "角色",
    prop: "roles",
    minWidth: 200,
    align: "left",
    slot: "roles"
  },
  {
    label: "状态",
    prop: "status",
    width: 110,
    slot: "status"
  },
  {
    label: "创建时间",
    prop: "created_at",
    minWidth: 180
  },
  {
    label: "最近登录",
    prop: "last_login_at",
    minWidth: 180
  },
  {
    label: "操作",
    prop: "operation",
    width: 220,
    slot: "operation",
    fixed: "right"
  }
];

export function useAccountPage() {
  const SYSTEM_ROLE_SLUGS = [
    "admin",
    "support",
    "system_admin",
    "super_admin",
    "service_operator"
  ];
  const dialogVisible = ref(false);
  const dialogTitle = ref("新增用户");
  const dialogFormRef = ref<FormInstance>();
  const dialogForm = reactive<AccountFormModel>({ ...DEFAULT_FORM });
  const saving = ref(false);

  const roleOptions = ref<Array<RoleItem>>([]);
  const roleLoading = ref(false);

  const {
    formState: filterForm,
    pagination,
    dataList,
    loading,
    onSearch,
    resetForm: resetFilter,
    handlePageChange,
    handleSizeChange
  } = useListPage<AccountFilterForm, AccountItem, AccountListResult>(
    {
      fetch: params =>
        accountsApi.fetchList({
          ...params,
          keyword: params.keyword,
          status: params.status,
          role_id: params.role_id,
          scope_type: "system"
        })
    },
    DEFAULT_FILTER,
    {},
    {
      responseAdapter: response => ({
        list: response.list,
        total: response.total,
        pageSize: response.pageSize,
        currentPage: response.currentPage
      })
    }
  );

  const tableData = computed(() => dataList.value ?? []);

  const dialogRules: FormRules<AccountFormModel> = {
    phone: [
      { required: true, message: "请输入手机号", trigger: "blur" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入合法的 11 位手机号",
        trigger: "blur"
      }
    ],
    nickname: [
      { required: true, message: "请输入昵称", trigger: "blur" },
      { min: 2, max: 32, message: "昵称长度限制为 2-32 位", trigger: "blur" }
    ],
    real_name: [
      { required: true, message: "请输入真实姓名", trigger: "blur" },
      {
        min: 2,
        max: 32,
        message: "真实姓名长度限制为 2-32 位",
        trigger: "blur"
      }
    ],
    email: [
      {
        type: "email",
        message: "请输入合法的邮箱地址",
        trigger: ["blur", "change"]
      }
    ],
    password: [
      {
        validator: (_rule, value, callback) => {
          if (dialogForm.id === 0 && !value) {
            callback(new Error("请输入登录密码"));
            return;
          }
          if (value && (value.length < 6 || value.length > 32)) {
            callback(new Error("密码长度需在 6-32 位"));
            return;
          }
          callback();
        },
        trigger: ["blur", "change"]
      }
    ],
    role_ids: [
      {
        type: "array",
        required: true,
        message: "请至少选择一个角色",
        trigger: "change"
      }
    ]
  };

  const handleSearch = async () => {
    filterForm.page = 1;
    await onSearch();
  };

  const handleResetFilters = async () => {
    await resetFilter();
  };

  const resetDialogForm = () => {
    Object.assign(dialogForm, { ...DEFAULT_FORM });
  };

  const openCreate = () => {
    dialogTitle.value = "新增用户";
    resetDialogForm();
    dialogVisible.value = true;
  };

  const openEdit = (row: AccountItem) => {
    dialogTitle.value = "编辑用户";
    resetDialogForm();
    dialogForm.id = row.id;
    dialogForm.phone = row.phone ?? "";
    dialogForm.nickname = row.nickname ?? "";
    dialogForm.real_name = row.real_name ?? "";
    dialogForm.email = row.email ?? "";
    dialogForm.status = Number(row.status ?? 1) as 0 | 1 | number;
    const allowedRoleIds = new Set(roleOptions.value.map(role => role.id));
    dialogForm.role_ids = ensureArray<any>(row.roles)
      .map(role => toNumber(role?.id, 0))
      .filter(id => id > 0 && allowedRoleIds.has(id));
    dialogVisible.value = true;
  };

  const submitForm = async () => {
    const formRef = dialogFormRef.value;
    if (!formRef) return;
    try {
      await formRef.validate();
    } catch {
      return;
    }

    const payload: AccountPayload = {
      phone: dialogForm.phone,
      nickname: dialogForm.nickname,
      real_name: dialogForm.real_name,
      email: dialogForm.email || null,
      status: dialogForm.status,
      role_ids: dialogForm.role_ids.slice(),
      remark: null
    };

    if (dialogForm.role_ids.length === 0) {
      message("请至少选择一个系统角色", { type: "warning" });
      return;
    }

    if (dialogForm.id === 0) {
      payload.password = dialogForm.password;
    } else if (dialogForm.password) {
      payload.password = dialogForm.password;
    }

    if (saving.value) return;
    saving.value = true;
    try {
      if (dialogForm.id === 0) {
        await accountsApi.create(payload);
        message("用户创建成功", { type: "success" });
      } else {
        await accountsApi.update(dialogForm.id, payload);
        message("用户信息已更新", { type: "success" });
      }
      dialogVisible.value = false;
      await onSearch();
    } catch (error: any) {
      message(error?.message ?? "保存用户失败", { type: "error" });
    } finally {
      saving.value = false;
    }
  };

  const handleDelete = async (row: AccountItem) => {
    try {
      await ElMessageBox.confirm(
        `确认删除用户「${row.phone ?? row.nickname ?? row.id}」吗？`,
        "删除确认",
        {
          type: "warning",
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      );
    } catch {
      return;
    }

    try {
      await accountsApi.remove(row.id);
      message("用户已删除", { type: "success" });
      await onSearch();
    } catch (error: any) {
      message(error?.message ?? "删除用户失败", { type: "error" });
    }
  };

  const handleToggleStatus = async (row: AccountItem) => {
    const nextStatus = row.status === 1 ? 0 : 1;
    try {
      await accountsApi.updateStatus(row.id, nextStatus);
      message(nextStatus === 1 ? "用户已启用" : "用户已禁用", {
        type: "success"
      });
      await onSearch();
    } catch (error: any) {
      message(error?.message ?? "更新状态失败", { type: "error" });
    }
  };

  const handleResetPassword = async (row: AccountItem) => {
    try {
      const { value } = await ElMessageBox.prompt(
        `请输入用户「${row.phone ?? row.nickname ?? row.id}」的新密码`,
        "重置密码",
        {
          inputType: "password",
          inputPlaceholder: "至少 6 位字符",
          showCancelButton: true,
          inputValidator: value => {
            if (!value || value.length < 6) {
              return "密码长度需至少 6 位";
            }
            return true;
          }
        }
      );
      await accountsApi.resetPassword(row.id, { password: value });
      message("密码已重置", { type: "success" });
    } catch (error: any) {
      if (error === "cancel" || error === "close") return;
      message(error?.message ?? "重置密码失败", { type: "error" });
    }
  };

  const loadRoles = async () => {
    roleLoading.value = true;
    try {
      const response: RoleListResult = await rolesApi.fetchList({
        page: 1,
        page_size: 100,
        scope_type: "system"
      });
      roleOptions.value = response.list
        .filter(role =>
          SYSTEM_ROLE_SLUGS.includes(
            (role.slug || role.code || "").toLowerCase()
          )
        )
        .sort((a, b) => a.id - b.id);
    } catch (error: any) {
      message(error?.message ?? "加载角色列表失败", { type: "error" });
    } finally {
      roleLoading.value = false;
    }
  };

  onMounted(async () => {
    await loadRoles();
    await onSearch();
  });

  return {
    // 列表
    filterForm,
    pagination,
    tableData,
    columns,
    loading,
    handleSearch,
    handleResetFilters,
    handlePageChange,
    handleSizeChange,

    // 角色选项
    roleOptions,
    roleLoading,

    // 弹窗
    dialogVisible,
    dialogTitle,
    dialogForm,
    dialogFormRef,
    dialogRules,
    openCreate,
    openEdit,
    submitForm,

    // 操作
    handleDelete,
    handleToggleStatus,
    handleResetPassword,

    statusOptions: STATUS_OPTIONS,
    saving
  };
}
